package com.tjh.springbootapi.utils;

import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * Create by koala on 2020-03-21
 */
public class FileDownloadUtil {

    /**
     * 下载模板
     *
     * @param response
     * @param downTemplateVehicle
     */
    public static void downTemplate(HttpServletResponse response, String downTemplateVehicle) {
        ClassPathResource resource = new ClassPathResource(downTemplateVehicle);
        try {
            if (resource.exists()) {
                int fileLength = (int) resource.contentLength();
                response.reset();//清空response
                response.setContentType("application/octet-stream;charset=utf-8");
                response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(resource.getFilename(), "UTF-8"));
                response.setHeader("Content-Length", String.valueOf(fileLength));
                InputStream inputStream = resource.getInputStream();
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[1024];
                while (inputStream.read(b) != -1) {
                    outputStream.write(b);
                }
                inputStream.close();
                outputStream.flush();
                outputStream.close();
                return;
            } else {
                response.setHeader("error", "file does not exist");
            }
        } catch (Exception e) {
            response.setHeader("error", e.getMessage());
            return;
        }
        response.setHeader("error", "index argument invalid");
    }
}
